package org.jeecg.modules.friends.user.controller;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.ControllerMethodCheck;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.friends.auth.dto.UserExtDTO;
import org.jeecg.modules.friends.auth.entity.UserAuthentication;
import org.jeecg.modules.friends.auth.service.IUserAuthenticationService;
import org.jeecg.modules.friends.enums.AuthStatusEnum;
import org.jeecg.modules.friends.enums.BaseInfoStatusEnum;
import org.jeecg.modules.friends.enums.EditTypeEnum;
import org.jeecg.modules.friends.service.InvitedUserService;
import org.jeecg.modules.friends.service.VipUserService;
import org.jeecg.modules.friends.user.dto.DetailEditDTO;
import org.jeecg.modules.friends.user.dto.HomePageUserDTO;
import org.jeecg.modules.friends.user.dto.InvitedUserInfo;
import org.jeecg.modules.friends.user.dto.MatchInfoDTO;
import org.jeecg.modules.friends.user.dto.SelfDetailInfoDTO;
import org.jeecg.modules.friends.user.dto.UserDetailInfoDTO;
import org.jeecg.modules.friends.user.entity.User;
import org.jeecg.modules.friends.user.param.DescriptionEditParam;
import org.jeecg.modules.friends.user.param.DetailInfoRequest;
import org.jeecg.modules.friends.user.param.HomePageUserRequest;
import org.jeecg.modules.friends.user.param.ModifyHeadPicParam;
import org.jeecg.modules.friends.user.param.OperateRecommend;
import org.jeecg.modules.friends.user.param.SelfDetailInfoEditParam;
import org.jeecg.modules.friends.user.param.UserEditParam;
import org.jeecg.modules.friends.user.param.UserLocationParam;
import org.jeecg.modules.friends.user.param.UserPicEditParam;
import org.jeecg.modules.friends.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 用户信息表
 * @Author: jeecg-boot
 * @Date: 2024-05-15
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "用户信息接口")
@RestController
@RequestMapping("/friends/user/")
public class UserController extends JeecgController<User, IUserService> {
    @Autowired
    private IUserService userService;

    @Autowired
    private VipUserService vipUserService;

    @Autowired
    private InvitedUserService invitedUserService;

    @Autowired
    private IUserAuthenticationService userAuthenticationService;

    /**
     * 编辑
     */
    @ApiOperation(value = "用户信息-编辑", notes = "用户信息-编辑")
    @RequestMapping(value = "/editInfo", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> editInfo(@RequestBody UserEditParam param, @RequestHeader(value = "token") String token) {
        User user = getUser(token);
        log.info("editInfo user {} , req {} ", JSON.toJSONString(user), JSON.toJSONString(param));
        int update = userService.updateUserInfo(param, user);
        userService.updateBaseInfoStatus(user.getId(), BaseInfoStatusEnum.auditing, null);
        if (update > 0) {
            return Result.OK("编辑成功!");
        }
        return Result.error("系统异常");
    }

    @ApiOperation(value = "用户详情", notes = "用户详情")
    @RequestMapping(value = "/detailInfo", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<HomePageUserDTO> detailInfo(@RequestBody DetailInfoRequest request,
            @RequestHeader(value = "token", required = false) String token) {
        User user;
        if (StringUtils.isNotEmpty(token)) {
            user = getUser(token);
        } else {
            user = null;
        }
        HomePageUserDTO detailEditDTO = userService.getDetailInfo(user, request.getUserId());
        return Result.OK(detailEditDTO);
    }

    @ApiOperation(value = "别人用户详情", notes = "别人用户详情")
    @RequestMapping(value = "/detailInfo/other", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<HomePageUserDTO> detailInfoOther(@RequestBody DetailInfoRequest request,
            @RequestHeader(value = "token", required = false) String token) {
        User user;
        if (StringUtils.isNotEmpty(token)) {
            user = getUser(token);
        } else {
            user = null;
        }
        HomePageUserDTO detailEditDTO = userService.getDetailInfo(user, request.getUserId());
        return Result.OK(detailEditDTO);
    }

    @ApiOperation(value = "自我描述编辑", notes = "自我描述编辑")
    @RequestMapping(value = "/editDescription", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> editDescription(@RequestBody DescriptionEditParam request,
            @RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        log.info("editDescription user {} , req {} ", JSON.toJSONString(user), JSON.toJSONString(request));
        if (request.getEditType() == EditTypeEnum.SELF_DESCRIPTION.getCode()) {
            userService.updateSelfDescription(request.getSelfDescription(), user);
        } else if (request.getEditType() == EditTypeEnum.FAMILY_DESCRIPTION.getCode()) {
            userService.updateFamilyDescription(request.getFamilyDescription(), user);
        } else if (request.getEditType() == EditTypeEnum.HOBBIES_DESCRIPTION.getCode()) {
            userService.updateHobbies(request.getHobbyDescription(), user);
        } else if (request.getEditType() == EditTypeEnum.LIFE_PARTNER_REQUIREMENTS.getCode()) {
            userService.updateLifePartnerRequirements(request.getLifePartnerRequirements(), user);
        }
        userService.updateBaseInfoStatus(user.getId(), BaseInfoStatusEnum.auditing, null);
        return Result.OK("编辑成功!");
    }

    @ApiOperation(value = "完善所有资料", notes = "完善所有资料")
    @RequestMapping(value = "/full/editDescription", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> editDescriptionFull(@RequestBody DescriptionEditParam request,
            @RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        if (request.isAnyBlank()) {
            return Result.error("对另一半的要求、家庭描述、兴趣爱好、昵称不能为空");
        }
        userService.updateFullInfo(request.getLifePartnerRequirements(), request.getFamilyDescription(),
                request.getHobbyDescription(), request.getNickName(), user);
        return Result.OK("编辑成功!");
    }


    @ApiOperation(value = "修改展示图片", notes = "展示自己接口")
    @RequestMapping(value = "/userPics", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> userPics(@RequestBody UserPicEditParam request, @RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        try {
            userService.updateUserPics(request.getUserPicDTOList(), user);
            userService.updateBaseInfoStatus(user.getId(), BaseInfoStatusEnum.auditing, null);
        } catch (Exception e) {
            return Result.error("编辑失败");
        }
        return Result.OK("编辑成功!");
    }

    @ApiOperation(value = "获取匹配信息", notes = "获取匹配信息")
    @RequestMapping(value = "/queryMatchInfo", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<MatchInfoDTO> queryMatchInfo(@RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }

        return Result.OK(new MatchInfoDTO());
    }

    /**
     * 首页推荐
     */
    @ApiOperation(value = "首页用户推荐信息", notes = "首页用户推荐信息")
    @RequestMapping(value = "/queryRecommendedUserInfo", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<HomePageUserDTO> queryRecommendedUserInfo(@RequestBody HomePageUserRequest request,
            @RequestHeader(value = "token", required = false) String token) {
        User user;
        if (StringUtils.isNotEmpty(token)) {
            user = getUser(token);
        } else {
            user = null;
        }
        HomePageUserDTO homePageUserDTO = userService.recommendUser(request, user);
        return Result.OK(homePageUserDTO);
    }

    @ApiOperation(value = "首页用户推荐信息", notes = "首页用户推荐信息")
    @RequestMapping(value = "/queryRecommendedUserInfo/V2", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<HomePageUserDTO> queryRecommendedUserInfoV2(@RequestBody HomePageUserRequest request,
            @RequestHeader(value = "token", required = false) String token) {
        User user;
        if (StringUtils.isNotEmpty(token)) {
            user = getUser(token);
        } else {
            user = null;
        }
        HomePageUserDTO homePageUserDTO = userService.recommendUser(request, user);
        if (request.existCondition() && homePageUserDTO == null) {
            HomePageUserDTO h = new HomePageUserDTO();
            h.setState(1);
            return Result.OK(h);
        }
        if (homePageUserDTO == null) {
            HomePageUserDTO h = new HomePageUserDTO();
            h.setState(2);
            return Result.OK(h);
        }
        homePageUserDTO.setState(3);
        return Result.OK(homePageUserDTO);
    }


    @ApiOperation(value = "我的-我的基本资料", notes = "基本资料")
    @RequestMapping(value = "/userDetailInfo", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<UserDetailInfoDTO> userDetailInfo(@RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        UserDetailInfoDTO detailInfoDTO = userService.getUserDetailInfo(user);
        return Result.OK(detailInfoDTO);
    }

    @ApiOperation(value = "修改头像", notes = "修改头像")
    @RequestMapping(value = "/modifyHeadPic", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> modifyHeadPic(@RequestHeader(value = "token") String token,
            @RequestBody ModifyHeadPicParam modifyHeadPicParam) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        user.setHeadPicUrl(modifyHeadPicParam.getHeadPicUrl());
        userService.updateById(user);
        return Result.OK();
    }

    @ApiOperation(value = "获取编辑基本资料", notes = "获取编辑基本资料")
    @RequestMapping(value = "/detailEditInfo", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<DetailEditDTO> detailEditInfo(@RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        DetailEditDTO detailInfoDTO = userService.getDetailEditDTO(user);
        return Result.OK(detailInfoDTO);
    }

    @ApiOperation(value = "自我展示信息获取", notes = "自我展示信息获取")
    @RequestMapping(value = "/selfDetailInfo", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<SelfDetailInfoDTO> selfDetailInfo(@RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        SelfDetailInfoDTO detailInfoDTO = userService.getSelfDetailInfo(user);
        return Result.OK(detailInfoDTO);
    }

    @ApiOperation(value = "自我展示信息编辑", notes = "自我展示信息编辑")
    @RequestMapping(value = "/selfDetailInfoEdit", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> selfDetailInfoEdit(@RequestBody SelfDetailInfoEditParam request,
            @RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        userService.updateSelfDetailInfo(request, user);
        userService.updateBaseInfoStatus(user.getId(), BaseInfoStatusEnum.auditing, null);
        return Result.OK("编辑成功");
    }


    @ApiOperation(value = "邀请记录", notes = "邀请记录")
    @RequestMapping(value = "/invitedRecord", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<List<InvitedUserInfo>> invitedRecord(@RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        List<InvitedUserInfo> invitedUserInfos = invitedUserService.queryByUserId(user.getId());
        return Result.OK(invitedUserInfos);
    }


    @ApiOperation(value = "开通vip", notes = "开通vip")
    @RequestMapping(value = "/addVipUser", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> addVipUser(@RequestBody DetailInfoRequest request, @RequestHeader(value = "token") String token) {
        User user = userService.findById(request.getUserId());
        vipUserService.addVipUser(user, 1, 7, System.currentTimeMillis() + 7 * 24 * 3600 * 1000L);
        return Result.OK();
    }

    @ApiOperation(value = "操作推荐", notes = "操作推荐")
    @RequestMapping(value = "/operateRecommend", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> operateRecommend(@RequestBody OperateRecommend operateRecommend,
            @RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        if (operateRecommend.getOperateType() == 1) {
            userService.updateRecommendStatus(user, true);
        } else if (operateRecommend.getOperateType() == 2) {
            userService.updateRecommendStatus(user, false);
        }

        return Result.OK();
    }

    @ApiOperation(value = "用户注销", notes = "用户注销")
    @RequestMapping(value = "/userLogoff", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> userLogoff(@RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        log.info("userLogoff user {}", JSON.toJSONString(user));
        userService.userLogoff(user, 1);
        return Result.OK();
    }

    @ApiOperation(value = "经纬度上传", notes = "经纬度上传")
    @RequestMapping(value = "/updateLocation", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> updateLocation(@RequestBody UserLocationParam request,
            @RequestHeader(value = "token") String token) {
        User user = getUser(token);
        if (user == null) {
            return Result.error("登录过期，请重新登录");
        }
        try {
            userService.updateLocation(user, request.getLat(), request.getLng());
        } catch (Exception e) {
            return Result.error("系统异常");
        }
        return Result.OK();
    }

    @ApiOperation(value = "经纬度上传", notes = "经纬度上传")
    @RequestMapping(value = "/userDataWash", method = {RequestMethod.POST})
    @ControllerMethodCheck
    public Result<?> userDataWash() {
        for (int i = 1; i < 5; i++) {
            Page<User> page = new Page<User>(i, 500);
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getAuthStatus, 50);
            Page<User> userList = userService.page(page, lambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(userList.getRecords())) {
                for (User user : userList.getRecords()) {
                    List<UserAuthentication> userAuthentications =
                            userAuthenticationService.selectByUserId(user.getId());
                    if (userAuthentications.size() < 3
                            || userAuthenticationService.queryUserAuthInfo(user).getAuthStatus()
                            != AuthStatusEnum.PASSED.getCode()) {
                        user.setAuthStatus(AuthStatusEnum.INITIALIZE.getCode());
                        UserExtDTO userExtDTO = JSONObject.parseObject(user.getExtData(), UserExtDTO.class);
                        userExtDTO.setIsFirstCommit(false);
                        userExtDTO.setShowInviteUrl(false);
                        userExtDTO.setAuthStatus(user.getAuthStatus());
                        user.setExtData(JSONObject.toJSONString(userExtDTO));
                        userService.updateById(user);
                    }
                }
            }
        }
        return Result.OK();
    }

    private User getUser(String token) {
        String mobile = JwtUtil.getMobile(token);
        User user = userService.getUserByPhone(mobile);
        return user;
    }

}
